from selenium.webdriver.common.by import By
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.webdriver.remote.webelement import WebElement
from qturboframe.lib.report.log import logger

from .base_element import BaseElement


class Menu(BaseElement):
    '''
    Jres2.0菜单操作
    
    :Attributes:
     - _driver: 控件所在的当前webdriver对象
     - _element: 控件元素webelement对象
     - timeout: 步骤操作的超时时间
     
    :Example:
     - 例1: Menu(webelement)
     - 例2: Menu({By.CLASS_NAME:'class_name','text':'文本信息'})
     - 例3: Menu({By.CLASS_NAME:'class_name','text':'文本信息'}, father=driver)
     - 例4: Menu({By.CLASS_NAME:'class_name','text':'文本信息'}, father=webelement)
    '''

    def __init__(self, element_para, father=None, timeout=5):
        super().__init__(element_para, father, timeout)

    def select(self, linkText, timeout=3):
        '''
        jres2.0的菜单栏链接，并切换到iframe

        :Args:
         - linkText: 菜单栏链接名称集合，按照顺序点击链接
         - timeout: 超时时间，默认30秒

        :Raises:
            SeleniumError: 菜单操作失败
            
        :Example:
         - 例: Menu.select("首页/客户信息/客户详细信息")
        '''
        try:
            # 保证菜单操作在最外层frame进行
            self._driver.switch_to.default_content()

            menus = linkText.split('/')
            #顶头菜单栏
            if len(menus) - 3 == 0:
                top_menu_div:WebElement = self._driver.find_element_by_attribute(By.CSS_SELECTOR, "#menuTop", timeout=self.timeout)
                menu_a_list = top_menu_div.find_elements_by_attribute(By.CSS_SELECTOR,"ul>li>a", timeout=self.timeout)
                for menu_temp in menu_a_list:
                    if menu_temp.text.strip() == menus[0]:
                        if 'uf-h-header-selected' not in menu_temp.get_attribute("class"):
                            menu_temp.click()
                        logger.debug('菜单"{}"已经打开'.format(menus[0]))
                        menus = menus[1:]
                        break

            #左边菜单栏第一级
            if len(menus) - 2 == 0:
                menu_a_list = self._driver.find_elements_by_attribute(By.XPATH, ".//div[@id='h-menu']//div[@class='h-menu-body']/ul[not(contains(@style,'display: none'))]/li/a/span", timeout=self.timeout)
                side_menu = None
                for menu_temp in menu_a_list:
                    text = menu_temp.text.strip() if menu_temp.text.strip() else menu_temp.get_attribute('innerText').strip()
                    if text==menus[0]:
                        li_tag = menu_temp.find_element_by_attribute(By.XPATH,".//ancestor::li", timeout=self.timeout)
                        side_menu = menu_temp.find_element_by_attribute(By.XPATH,".//ancestor::li/ul[@class='h_sub-menu']", timeout=self.timeout)
                        if "active" not in side_menu.get_attribute("class"):
                            li_tag.click()
                        logger.debug('菜单"{}"已经打开'.format(menus[0]))
                        menus = menus[1:]
                        break
                
                if not side_menu:
                    logger.debug('没有找到此"{}"菜单'.format(menus[0]))
                
                b_find=False
                if len(menus) - 1 == 0:
                    sub_menu_a_list = side_menu.find_elements_by_attribute(By.XPATH, "./li/a")
                    for sub_menu_temp in sub_menu_a_list:
                        text = sub_menu_temp.text.strip() if sub_menu_temp.text.strip() else sub_menu_temp.get_attribute('innerText').strip()
                        if text == menus[0]:
                            b_find = True
                            base_element = BaseElement(sub_menu_temp)
                            base_element.click()
                            logger.debug('菜单"{}"已经打开'.format(menus[0]))
                            break
                    if not b_find:
                        logger.debug('没有找到此"{}"菜单'.format(menus[0]))
        except Exception as msg:
            raise SeleniumError(str(msg))

    def select_actp(self, linkText):
        '''
        BOP受理端菜单操作，并切换到iframe

        :Args:
         - linkText: 菜单栏链接名称集合，按照顺序点击链接
         - timeout: 超时时间，默认30秒

        :Raises:
            SeleniumError: 菜单操作失败

        :Example:
         - 例: Menu.select_actp("首页/客户信息/客户详细信息")
        '''
        # 保证菜单操作在最外层frame进行
        self._driver.switch_to.default_content()

        menu_list = linkText.split("/")

        #保存当前点击的li tag
        current_li_tag = None
        if len(menu_list)!=0:
            #top menu
            locator = "ul.top-nav>li"
            top_menu_li_tags = self._driver.find_elements_by_attribute(By.CSS_SELECTOR, locator, timeout=self.timeout)
            for top_menu_li_tag in top_menu_li_tags:
                if BaseElement(top_menu_li_tag).get_text().strip() == menu_list[0].strip():
                    current_li_tag = top_menu_li_tag
                    BaseElement(top_menu_li_tag).click()
                    logger.debug("点击菜单:{}".format(menu_list[0]))
                    menu_list = menu_list[1:]
                    break

        if len(menu_list) !=0:
            #top菜单是否有子菜单
            li_dropdown_menu = current_li_tag.exist(By.CSS_SELECTOR, "ul.dropdown-menu", timeout=0.1)
            if li_dropdown_menu:
                #点击top menu的子菜单
                dropdown_lis = current_li_tag.find_elements_by_attribute(By.XPATH,"./li[not(@class,'divider')]", timeout=self.timeout)
                for dropdown_li in dropdown_lis:
                    if BaseElement(dropdown_li).get_text().strip()==menu_list[0]:
                        BaseElement(dropdown_li).click()
                        logger.debug("点击菜单:{}".format(menu_list[0]))
                        break
            else:
                #点击侧边菜单
                xpath = ".//ul[contains(@class='left-menu')]/li[not(contains(@style,'display: none;'))]"
                left_menu_li_tags = self._driver.find_elements_by_attribute(By.XPATH, xpath, timeout=self.timeout)
                #存储左侧的一级菜单
                current_sub_menu = None
                for left_menu_li_tag in left_menu_li_tags:
                    if BaseElement(left_menu_li_tag).get_text().strip() == menu_list[0].strip():
                        current_sub_menu = left_menu_li_tag
                        BaseElement(left_menu_li_tag).click()
                        logger.debug("点击菜单:{}".format(menu_list[0]))
                        menu_list = menu_list[1:]
                        break

                if current_sub_menu:
                    xpath = "./following-sibling::li//ul/li"
                    sub_menu_li_tags = current_sub_menu.find_element_by_attribute(By.XPATH, xpath, timeout=self.timeout)
                    for sub_menu_li_tag in sub_menu_li_tags:
                        if BaseElement(sub_menu_li_tag).get_text().strip()==menu_list[0].strip():
                            BaseElement(sub_menu_li_tag).click()
                            logger.debug("点击菜单:{}".format(menu_list[0]))
                            break
                    else:
                        raise SeleniumError("没有找到左侧菜单：“{}”".format(menu_list[0]))

                else:
                    raise SeleniumError("没有找到左侧菜单：“{}”".format(menu_list[0]))





